import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { join } from 'path';
import * as fs from 'fs';
import * as multer from 'multer';
import { File } from '../../entities/file.entity';
import { CreateFileDto, UpdateFileDto } from './dto';
import { Task } from '../../entities/task.entity';
import { v4 as uuidv4 } from 'uuid';

@Injectable()
export class FileService {
  constructor(
    @InjectRepository(File)
    private fileRepository: Repository<File>,
    @InjectRepository(Task)
    private taskRepository: Repository<Task>,
  ) {}

  createMulterStorage() {
    return multer.diskStorage({
      destination: function (req, file, cb) {
        const uploadPath = join(process.cwd(), 'uploads');
        
        // 确保上传目录存在
        if (!fs.existsSync(uploadPath)) {
          fs.mkdirSync(uploadPath, { recursive: true });
        }
        
        cb(null, uploadPath);
      },
      filename: function (req, file, cb) {
        const uniqueSuffix = uuidv4();
        const fileExtension = file.originalname.split('.').pop();
        cb(null, `${uniqueSuffix}.${fileExtension}`);
      },
    });
  }

  async create(
    file: Express.Multer.File,
    createFileDto: CreateFileDto,
    userId: string,
  ) {
    const { taskId, description } = createFileDto;

    // 如果提供了taskId，确认任务存在
    if (taskId) {
      const task = await this.taskRepository.findOne({ where: { id: taskId } });
      if (!task) {
        throw new NotFoundException(`未找到ID为${taskId}的任务`);
      }
    }

    // 创建文件记录
    const fileEntity = this.fileRepository.create({
      originalName: file.originalname,
      filename: file.filename,
      path: file.path.replace(`${process.cwd()}\\`, '').replace(/\\/g, '/'),
      mimeType: file.mimetype,
      size: file.size,
      description,
      uploaderId: userId,
      taskId,
    });

    return this.fileRepository.save(fileEntity);
  }

  async findAll() {
    return this.fileRepository.find();
  }

  async findByTask(taskId: string) {
    return this.fileRepository.find({
      where: { taskId },
      order: { createdAt: 'DESC' },
    });
  }

  async findOne(id: string) {
    const file = await this.fileRepository.findOne({ where: { id } });
    if (!file) {
      throw new NotFoundException(`未找到ID为${id}的文件`);
    }
    return file;
  }

  async update(id: string, updateFileDto: UpdateFileDto) {
    const file = await this.findOne(id);
    
    // 如果要更新taskId，先确认任务存在
    if (updateFileDto.taskId) {
      const task = await this.taskRepository.findOne({ 
        where: { id: updateFileDto.taskId } 
      });
      if (!task) {
        throw new NotFoundException(`未找到ID为${updateFileDto.taskId}的任务`);
      }
    }
    
    Object.assign(file, updateFileDto);
    return this.fileRepository.save(file);
  }

  async remove(id: string) {
    const file = await this.findOne(id);
    
    // 尝试删除物理文件
    try {
      const filePath = join(process.cwd(), file.path);
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    } catch (error) {
      console.error('删除文件时出错：', error);
    }
    
    return this.fileRepository.remove(file);
  }
}
